import { http } from "./http.js";
import { EventTarget } from "./eventTarget.js";
import { Visitor } from "./visitor.js";
import { Agent } from "./agent.js";
import { Message } from "./message.js";
import { html2dom } from "./html2dom.js";

export class Conversation extends EventTarget {
    constructor(app, d) {
        super();
        this.app = app;
        this.d = d;
        this.agent = new Agent(d.agentId, null, null);
        this.id = d.id;
        this.createTime = d.createTime;
        this.messages = [];
        this.bound = false;//chatwindow事件是否绑定
        this.lastMessage = {
            visitorId: d.visitorId,
            agentId: d.agentId,
            sendBy: d.lastSendBy,
            content: d.lastSendContent,
            sendTime: new Date(d.updateTime),
        };
        this._convListItemDOM = null;
        this._chatWindowDOM = null;
    }
    chatWindowDOM() {
        if (this._chatWindowDOM == null) {
            var headHtml = this.chatWindowHeadHtml();
            var html = headHtml + this.chatWindowBodyHtml();
            this._chatWindowDOM = html2dom.h2d(`<div class='css-b95f0i'>${html}</div>`);
            this._sendButton = this._chatWindowDOM.querySelector('.sendButton');
            this._chatInput = this._chatWindowDOM.querySelector('.chatInput');
            this._sendButton.onclick = () => this.doSend();
            this._chatInput.onkeyup = (e) => this.onChatInput(e);
        }
        return this._chatWindowDOM;
    }
    onChatInput(e) {
        if (this._chatInput.value.length > 0) {
            this._sendButton.removeAttribute('disabled');
        }
        else {
            this._sendButton.setAttribute("disabled", "disabled");
        }
    }
    doSend() {
        var text = this._chatInput.value;
        if (text.length > 0) {
            this.sendMessage(text);
            this._chatInput.value = '';
            this.onChatInput();
        }
    }
    convListItemDOM() {
        if (this._convListItemDOM == null) {
            this._convListItemDOM = document.createRange().createContextualFragment(this.html()).firstChild;
        }
        return this._convListItemDOM;
    }
    deactiveListItem() {
        this._convListItemDOM.classList.remove('css-avf3sp')
        this._convListItemDOM.classList.add("css-lykxrn")
    }
    activeListItem() {
        this._convListItemDOM.classList.add('css-avf3sp')
        this._convListItemDOM.classList.remove("css-lykxrn")
    }
    onMessage(d) {
        //新消息
        var m = new Message(d);
        this.messages.push(m);
        this.dispatchEvent({ type: 'message', msg: m });
        var mdom = m.dom();
        this._chatWindowDOM.querySelector(".messageList").appendChild(mdom);
        mdom.scrollIntoView();
        return m;
    }

    html() {
        let sendUser = this.lastMessage.sendBy == 'visitor' ? this.lastMessage.visitorId : this.agent.id;
        //css-lykxrn unselected
        //css-avf3sp selected
        return `<div class="css-lykxrn e107lob30">
            <div class="css-70qvj9 e107lob30">
                <div class=" css-9d6mok">
                    <div class="css-1plwehk">
                        <div class="css-1eqqbrm">${this.lastMessage.visitorId}</div>
                    </div>
                </div>
            </div>
            <div class="css-14929ed">
                <div class="css-mv2mbg emapx6b0"><span class="css-1nf6hhs">${sendUser}</span>
                    <div class="css-fipiow">${this.lastMessage.sendTime}</div>
                </div>
                <div class="css-mv2mbg emapx6b0">
                    <div class="css-xjt5o8">
                        <div class="css-19sxii8">
                            <span>${this.lastMessage.content}</span></div>
                    </div>
                    <div class="css-d0uhtl">
                        <span class="css-1ml7vf7 ss-badge ss-badge-not-a-wrapper">
                            <sup data-show="true" class="ss-scroll-number ss-badge-count" title="1">
                                <span class="ss-scroll-number-only" style="transform: translateY(-1100%);">
                                    <p class="ss-scroll-number-only-unit">
                                        0
                                    </p>
                                    <p class="ss-scroll-number-only-unit">
                                        1
                                    </p>
                                    <p class="ss-scroll-number-only-unit">
                                        2
                                    </p>
                                    <p class="ss-scroll-number-only-unit">
                                        3
                                    </p>
                                    <p class="ss-scroll-number-only-unit">
                                        4
                                    </p>
                                    <p class="ss-scroll-number-only-unit">
                                        5
                                    </p>
                                    <p class="ss-scroll-number-only-unit">
                                        6
                                    </p>
                                    <p class="ss-scroll-number-only-unit">
                                        7
                                    </p>
                                    <p class="ss-scroll-number-only-unit">
                                        8
                                    </p>
                                    <p class="ss-scroll-number-only-unit">
                                        99
                                    </p>
                                    <p class="ss-scroll-number-only-unit">
                                        0
                                    </p>
                                    <p class="ss-scroll-number-only-unit current">
                                        1
                                    </p>
                                </span>
                            </sup>
                        </span>
                    </div
                </div>
            </div>
        </div>`;
    }

    endConversation() {
        http.request(`/app/conversation/end?convid=${this.id}`)
            .then(d => this.onEndConversation(d));
    };

    onEndConversation(d) {

    }

    getMessages(page, size) {
        return http.request(`/app/conversation/messages?convid=${this.id}&page=${page}&size=${size}`)
            .then((d) => this.onGetMessages(JSON.parse(d)));
    }

    onGetMessages(d) {
        for (let i = 0; i < d.length; i++) {
            const element = d[i];
            this.messages.push(new Message(element));
        }
        this.app.onConversationUpdate(this);
    }

    sendMessage(d) {
        var mToSend = {
            id: new Date().getTime(), //id of the item on ui, will update if success
            content: d,
            sendBy: "agent",
            convId: this.id,
            sendTime: new Date(),
            visitorId: this.d.visitorId,
            agentId: this.d.agentId
        };
        this.onMessage(mToSend);
        http.post(`/app/conversation/send?convid=${this.id}&t=${mToSend.id}`, mToSend)
            .then(d => this.onSendMessage(JSON.parse(d, mToSend.id)));
    }

    onSendMessage(d, elementId) {
        console.log(d);
        console.log(elementId);
    }


    messagesHtml() {
        return this.messages.map(x => x.d.sendBy == "visitor" ? x.htmlVisitor() : x.html()).join();
    }

    chatWindowBodyHtml() {
        return `<div class="css-oaqive"><input accept="application/msword,application/pdf,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation,application/vnd.apple.keynote,application/x-iwork-keynote-sffkey,application/xml,image/*,text/csv,text/plain,text/xml,video/mp4,video/quicktime" multiple="" type="file" autocomplete="off" tabindex="-1" style="display: none;">
        <div class="css-4z6nar">
            <div class="messageList">
            ${this.messagesHtml()}
            </div>
            <div class="clear"></div>
            <div></div>
        </div>
        <div>
            <div>
                <div class="css-ytb6j6 e107lob30">
                <textarea placeholder="Send email to a@b.com" rows="1" class="css-1jauly chatInput" style="height: 37px !important;"></textarea>
                    <div width="100%" class="css-1c0vqx3 e107lob30">
                        <div class="css-k008qs e107lob30"><button class="Button css-7qpdim" type="button"><input accept="application/msword,application/pdf,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation,application/vnd.apple.keynote,application/x-iwork-keynote-sffkey,application/xml,image/*,text/csv,text/plain,text/xml,video/mp4,video/quicktime" multiple="" type="file" autocomplete="off" tabindex="-1" style="display: none;"><svg viewBox="0 0 24 24" display="inline-flex" color="currentColor" role="presentation" font-size="3" class="css-t64kfi">
                                    <path d="M16.5,6V17.5A4,4 0 0,1 12.5,21.5A4,4 0 0,1 8.5,17.5V5A2.5,2.5 0 0,1 11,2.5A2.5,2.5 0 0,1 13.5,5V15.5A1,1 0 0,1 12.5,16.5A1,1 0 0,1 11.5,15.5V6H10V15.5A2.5,2.5 0 0,0 12.5,18A2.5,2.5 0 0,0 15,15.5V5A4,4 0 0,0 11,1A4,4 0 0,0 7,5V17.5A5.5,5.5 0 0,0 12.5,23A5.5,5.5 0 0,0 18,17.5V6H16.5Z">
                                    </path>
                                </svg></button>
                            <div role="tooltip" tabindex="0"><button class="Button css-7qpdim" type="button" aria-expanded="false"><svg viewBox="0 0 24 24" display="inline-flex" color="currentColor" role="presentation" font-size="3" class="css-13sdj5a">
                                        <path d="M20,12A8,8 0 0,0 12,4A8,8 0 0,0 4,12A8,8 0 0,0 12,20A8,8 0 0,0 20,12M22,12A10,10 0 0,1 12,22A10,10 0 0,1 2,12A10,10 0 0,1 12,2A10,10 0 0,1 22,12M10,9.5C10,10.3 9.3,11 8.5,11C7.7,11 7,10.3 7,9.5C7,8.7 7.7,8 8.5,8C9.3,8 10,8.7 10,9.5M17,9.5C17,10.3 16.3,11 15.5,11C14.7,11 14,10.3 14,9.5C14,8.7 14.7,8 15.5,8C16.3,8 17,8.7 17,9.5M12,17.23C10.25,17.23 8.71,16.5 7.81,15.42L9.23,14C9.68,14.72 10.75,15.23 12,15.23C13.25,15.23 14.32,14.72 14.77,14L16.19,15.42C15.29,16.5 13.75,17.23 12,17.23Z">
                                        </path>
                                    </svg></button></div>
                            <div role="button" aria-expanded="false"><button class="Button css-7qpdim" type="button" data-userpilot="insert-shortcut-button"><svg viewBox="0 0 24 24" display="inline-flex" color="currentColor" role="presentation" font-size="3" class="css-13sdj5a">
                                        <path d="M4,2H20A2,2 0 0,1 22,4V16A2,2 0 0,1 20,18H16L12,22L8,18H4A2,2 0 0,1 2,16V4A2,2 0 0,1 4,2M4,4V16H8.83L12,19.17L15.17,16H20V4H4M6,7H18V9H6V7M6,11H16V13H6V11Z">
                                        </path>
                                    </svg></button></div>
                        </div>
                        <div class="css-k008qs e107lob30">
                            <div class="css-gmuwbf e107lob30">
                                <div role="group" class="css-vxcmzt">
                                <button class="Button Button--primary Button--small css-1bvutj9 sendButton" type="button" disabled="">
                                        <div class="css-qt5etv e107lob30"><svg viewBox="0 0 24 24" display="inline-flex" color="currentColor" role="presentation" font-size="2" class="css-q3febz">
                                                <path d="M20,8L12,13L4,8V6L12,11L20,6M20,4H4C2.89,4 2,4.89 2,6V18A2,2 0 0,0 4,20H20A2,2 0 0,0 22,18V6C22,4.89 21.1,4 20,4Z">
                                                </path>
                                            </svg>
                                            <div class="css-1cud95l e8amzt60">发送</div>
                                        </div>
                                    </button><button class="Button Button--primary Button--small css-fu3wfu" type="button" disabled="" aria-expanded="false"><svg viewBox="0 0 24 24" display="inline-flex" color="currentColor" role="presentation" font-size="2" class="css-q3febz">
                                            <path d="M7.41,15.41L12,10.83L16.59,15.41L18,14L12,8L6,14L7.41,15.41Z">
                                            </path>
                                        </svg></button></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div height="18px" class="css-141jgsa e107lob30">
            <div class="css-1fudwk" font-weight="normal">New line <code>enter</code></div>
        </div>
    </div>`;
    }

    chatWindowHeadHtml() {
        return `<div height="72" class="css-2lg4mp e107lob30">
        <div class="css-k008qs e107lob30">
            <div class=" css-9d6mok">
                <div class="css-1plwehk">
                    <div class="css-1eqqbrm">${this.d.visitorId}</div>
                </div>
            </div>
            <div class="css-qse2ks e107lob30">
                <div font-weight="bold" class="css-ujy0ws">${this.d.visitorId}</div>
                <div font-size="11px" font-weight="normal" class="css-1h82xgj">${this.d.visitorLastSendTime}</div>
            </div>
        </div>
        <div class="css-k008qs e107lob30">
            <div>
                <div class="Dropdown" data-cy="assign-conversation-dropdown">
                    <div role="button" class="Dropdown__toggler"><button class="Button Button--small css-1xx5rl8" type="button">
                            <div class="css-u4p24i e107lob30">
                                <div font-size="2" class="css-zn80rd e107lob30"><svg viewBox="0 0 24 24" display="inline-flex" color="currentColor" role="presentation" class="css-154karu">
                                        <path d="M12,4A4,4 0 0,1 16,8A4,4 0 0,1 12,12A4,4 0 0,1 8,8A4,4 0 0,1 12,4M12,14C16.42,14 20,15.79 20,18V20H4V18C4,15.79 7.58,14 12,14Z">
                                        </path>
                                    </svg></div>Assign<div font-size="2" class="css-zb1dh9 e107lob30"><svg viewBox="0 0 24 24" display="inline-flex" color="currentColor" role="presentation" class="css-154karu">
                                        <path d="M7.41,8.58L12,13.17L16.59,8.58L18,10L12,16L6,10L7.41,8.58Z">
                                        </path>
                                    </svg></div>
                            </div>
                        </button></div>
                </div>
            </div><button class="Button Button--small css-16uziep" type="button" data-cy="end-chat"><span font-weight="normal" class="css-l1c51u"><svg viewBox="0 0 24 24" display="inline-flex" color="currentColor" role="presentation" class="css-154karu">
                        <path d="M21,7L9,19L3.5,13.5L4.91,12.09L9,16.17L19.59,5.59L21,7Z">
                        </path>
                    </svg></span>Resolve</button>
            <div>
                <div class="Dropdown">
                    <div role="button" class="Dropdown__toggler"><button type="button" data-cy="chat-more" class="css-8de9qj"><svg viewBox="0 0 24 24" display="inline-flex" color="currentColor" role="presentation" class="css-154karu">
                                <path d="M16,12A2,2 0 0,1 18,10A2,2 0 0,1 20,12A2,2 0 0,1 18,14A2,2 0 0,1 16,12M10,12A2,2 0 0,1 12,10A2,2 0 0,1 14,12A2,2 0 0,1 12,14A2,2 0 0,1 10,12M4,12A2,2 0 0,1 6,10A2,2 0 0,1 8,12A2,2 0 0,1 6,14A2,2 0 0,1 4,12Z">
                                </path>
                            </svg></button></div>
                </div>
            </div>
        </div>
    </div>`
    }
}